<script setup lang="ts">
import { ElMessage } from 'element-plus';
import { watch, ref } from 'vue';
import { sysFileInfoMultipleUpload, sysFileInfoPage, sysFileInfoDelete, sysFileInfoPreviewBase64 } from '/@/api/centerControl/pubilc';
import { deleteProjectFileApiV2, getProjectDetailApi, uploadProjectFileApiV2 } from '/@/api/sms/HazardousChemicalsInterface';
const props = defineProps<{
	showInfoDialog: boolean;
	infoData: any;
	currentRecord:any
}>();

const emits = defineEmits<{
	(event: 'closeDialog'): void;
	(event: 'uploadFileTodoItemChange'): void;
}>();

const showInfoDialog = ref(false);
const infoData = ref<any>();

const close = () => {
	rest()
	fileData.value = [];
	sourceTodoId1.value = ''
	sourceTodoId.value = ''
	projectId.value = 0
	options1.value = []
	emits('closeDialog');
};

const newData = ref()
watch(
	() => props.infoData,
	(val) => {
		showInfoDialog.value = val;
		infoData.value = props.infoData;
		newData.value = props.infoData
		console.log('数据更新');
	},
	{
		immediate: true,
		deep: true,
	}
);

const currentRecord = ref()
watch(
	() => props.currentRecord,
	(val) => {
		currentRecord.value = props.currentRecord;
		console.log('数据更新');
	},
	{
		immediate: true,
		deep: true,
	}
);

// 切换阶段
const stageName = ref('全部阶段')
const activeStage = () => {
	//infoData.value
	stageName.value  == '全部阶段' ? stageName.value  = '当前阶段' : stageName.value  = '全部阶段'
	if(stageName.value  != '全部阶段'){
		infoData.value = newData.value.filter((item:any) => {
				return item.stage_Name == currentRecord.value.stage_Name
		})
	}else{
		infoData.value = newData.value.map((item:any) => {
			return item
		}
)
	}
}

const options1: any = ref([]);
const downTodoItemClick = (row: any) => {
	activeName.value = 'upload'
	fileData.value = [];
	options1.value = [];
	sourceTodoId.value = ''
	sourceTodoId1.value = ''
	if (!row.canDo) {
		sourceTodoId1.value = '';
		sourceTodoId.value = '';
		return ElMessage.warning('当前阶段代办不能上传文件');
	}
	if (!row.subItems.length) {
		sourceTodoId1.value = '';
		sourceTodoId.value = '';
		return ElMessage.warning('当前阶段代办没有阶段代办子项');
	}
	projectId.value = row.n_Id;
	options1.value = row.subItems.map((e) => {
		return {
			id: e.stageTodoSubItemId,
			label: e.stageTodoSubItemName,
			value: e.n_Id,
			files: e.v_FilePath,
		};
	});
};

let fileList: any = ref([]);
const formUploadData: any = ref([]);
const handleChange = (file: any) => {
	fileList.value.push(file);
};
const sourceTodoId = ref('');
const handleSave = async () => {
	if(!sourceTodoId.value) return ElMessage.warning('请选择阶段代办子项');
	if (fileList.value.length !== 0) {
		fileList.value.forEach((i: any) => {
			formUploadData.value.push(i.raw);
		});
		let prams = {
			Files: formUploadData.value,
			ProjectTodoId: projectId.value,
			SourceId: sourceTodoId.value,
		};
		console.log(prams, fileList.value);

		const res = await uploadProjectFileApiV2(prams);
		if (res.success) {
			ElMessage.success(res.message);
			rest();
			emits('uploadFileTodoItemChange');
		}
	}
};
const rest = () => {
	sourceTodoId.value = '';
	handleRemove(fileList.value);
	fileList.value = [];
	formUploadData.value = [];
};

const fileData = ref([]);
const sourceTodoId1 = ref('');
const handleQuery = () => {
	fileData.value = [];
	options1.value = [];
	infoData.value.forEach((i) => {
		if (i.n_Id == projectId.value) {
			if (i.subItems.length) {
				i.subItems.forEach((e) => {
					options1.value.push({
						id: e.stageTodoSubItemId,
						label: e.stageTodoSubItemName,
						value: e.n_Id,
						files: e.v_FilePath,
					});
				});
			}
		}
	});

	options1.value.forEach((e) => {
		if (e.value == sourceTodoId1.value) {
			fileData.value = e.files;
		}
	});
	console.log(fileData.value,"1111");
};

// 附件下载
const activeName = ref('upload');
const handleClick = () => {};

let refFile = ref();

const handleRemove = (file: any) => {
	console.log(file, 'file');
	fileList.value.map((itm: any, inx: number) => {
		if (file.uid === itm.uid) {
			fileList.value.splice(inx, 1);
		}
	});
	console.log(refFile.value);
	refFile.value?.handleRemove(file);
};

/*** downClick 下载文件 */
const downClick = async (val: any) => {
	let getFile = getFileFun(val.id);
	// 等待getFileFun完成
	await getFile;
	if (getFile && getFile.then) {
		getFile.then((res) => {
			let base64Data = res;
			let blob = base64ToBlob(base64Data);
			// 创建可下载的链接
			let url = URL.createObjectURL(blob);
			let link = document.createElement('a');
			link.href = url;
			link.download = val.fileOriginName; // 指定下载的文件名

			// 将链接添加到DOM中
			document.body.appendChild(link);

			// 触发点击事件开始下载
			link.click();

			// 释放临时URL
			URL.revokeObjectURL(url);
		});
	}
};
// 将Base64编码数据转换为Blob对象的辅助函数
const base64ToBlob = (base64Data: any) => {
	var byteString = atob(base64Data.split(',')[1]); // 提取Base64编码的数据部分
	var mimeString = base64Data.split(':')[1].split(';')[0]; // 提取MIME类型
	var ab = new ArrayBuffer(byteString.length);
	var ia = new Uint8Array(ab);
	for (var i = 0; i < byteString.length; i++) {
		ia[i] = byteString.charCodeAt(i);
	}
	return new Blob([ab], { type: mimeString });
};

/*** delClick 删除文件事件 */
const projectId = ref(0);
const delClick = async (val: Number) => {
	let param: any = {
		fileId: val || 0, // 文件id
		projectTodoId: projectId.value, // 项目代办id
	};
	await deleteProjectFileApiV2(param);
	await emits('uploadFileTodoItemChange');
	setTimeout(()=>{handleQuery()},1000)
};

/*** viewClick 文件预览 */
const baseUrl = import.meta.env.VITE_API_URL;
const viewClick = async (val: any) => {
	let viewUrl = baseUrl + '/' + val.path;
	window.open(viewUrl);
};

</script>
<template>
	<el-dialog v-model="showInfoDialog" title="资料填报" width="80%" style="min-height: 420px;" @close="close">
		<!-- <el-divider content-position="left"> 基本信息 </el-divider> -->
		<el-row :gutter="35">
			<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
				<el-button @click="activeStage" style="margin-bottom:10px" type="primary">{{stageName}}</el-button>
				<el-table :data="infoData" border style="width: 100%" height="400">
					<el-table-column align="center" type="index" label="序号" width="60" />
					<el-table-column align="center" prop="stage_Name" :show-overflow-tooltip="true" label="阶段名称" min-width="60" />
					<el-table-column align="center" prop="stageTodo_Name" :show-overflow-tooltip="true" label="待办名称" min-width="60" />
					<el-table-column align="center" prop="documentName" :show-overflow-tooltip="true" label="是否可上传" min-width="90">
						<template v-slot="scope">
							<el-tag v-if="scope.row.canDo" type="success">是</el-tag>
							<el-tag v-else type="danger">否</el-tag>
						</template>
					</el-table-column>
					<el-table-column align="center" prop="documentName" :show-overflow-tooltip="true" label="资料填报情况" min-width="100">
						<template v-slot="scope">
							<el-tag v-if="scope.row.isDone" type="success">完整</el-tag>
							<el-tag v-else type="danger">缺失</el-tag>
						</template>
					</el-table-column>
					<el-table-column label="操作" align="center" min-width="90">
						<template #default="scope">
							<el-button text size="small" icon="ele-Edit" type="primary" @click="downTodoItemClick(scope.row)">上传文件</el-button>
						</template>
					</el-table-column>
				</el-table>
			</el-col>
			<el-col :xs="12" :sm="12" :md="12" :lg="12" :xl="12">
				<el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
					<el-tab-pane label="文件上传" name="upload">
						<el-form v-if="options1.length" class="box-f w-h-100" :inline="true">
							<el-row :gutter="20">
								<el-col :xs="16" :sm="16" :md="16" :lg="16" :xl="16" class="mb20">
									<el-form-item label="阶段代办子项">
										<el-select v-model="sourceTodoId" class="m-2" placeholder="请选择阶段代办子项" >
											<el-option v-for="item in options1" :key="item.value" :label="item.label" :value="item.value" />
										</el-select>
									</el-form-item>
								</el-col>
								<el-col :xs="8" :sm="8" :md="8" :lg="8" :xl="8" class="mb20">
									<el-form-item>
										<el-button type="primary" @click="handleSave">保存文件</el-button>
									</el-form-item>
								</el-col>
							</el-row>
						</el-form>
						<div style="color: red; margin-bottom: 30px">注意：请先点击对应的上传文件按钮上传文件，上传文件成功后确认无误即可点击保存文件按钮</div>
						<el-upload v-if="options1.length" action="#" ref="refFile" list-type="picture-card" :auto-upload="false" :on-change="handleChange" multiple class="upload-s">
							<el-icon>
								<Plus />
							</el-icon>
							<template #file="{ file }">
								<template v-if="file.name.split('.')[1] === 'jpeg' || file.name.split('.')[1] === 'jpg' || file.name.split('.')[1] === 'png'">
									<img class="el-upload-list__item-thumbnail" :src="file.url" alt="" />
								</template>
								<template v-else>
									<span class="file-s">{{ file.name }}</span>
								</template>
								<span class="el-upload-list__item-actions set-bg" style="background-color: rgba(0, 0, 0, 0.5) !important">
									<span class="el-upload-list__item-delete" @click="handleRemove(file)" style="background: rgba(0, 0, 0, 0.5) !important">
										<el-icon>
											<Delete />
										</el-icon>
									</span>
								</span>
							</template>
						</el-upload>
					</el-tab-pane>
					<el-tab-pane label="文件下载" name="download">
						<el-form v-if="options1.length" label-width="100px" class="box-f w-h-100" :inline="true">
							<el-row :gutter="35">
								<el-col :xs="16" :sm="16" :md="16" :lg="16" :xl="16" class="mb20">
									<el-form-item label="阶段代办子项">
										<el-select v-model="sourceTodoId1" class="m-2" placeholder="请选择阶段代办子项" >
											<el-option v-for="item in options1" :key="item.value" :label="item.label" :value="item.value" />
										</el-select>
									</el-form-item>
								</el-col>
								<el-col :xs="8" :sm="8" :md="8" :lg="8" :xl="8" class="mb20">
									<el-form-item>
										<el-button type="primary" @click="handleQuery">查询</el-button>
									</el-form-item>
								</el-col>
							</el-row>
						</el-form>
						<el-table v-if="options1.length" class="heightcss" :data="fileData" style="width: 100%" element-loading-background="rgba(0, 0, 0, 0.5)" border>
							<el-table-column prop="fileName" label="文件名称" min-width="120" align="center" :show-overflow-tooltip="true" />
							<el-table-column prop="createdTime" label="上传时间" min-width="120" align="center" :show-overflow-tooltip="true" />
							<el-table-column prop="createdUserName" label="上传人" min-width="120" align="center" :show-overflow-tooltip="true" />
							<el-table-column fixed="right" prop="operation" label="操作" show-overflow-tooltip min-width="120" align="center">
								<template #default="scope">
									<el-button @click="viewClick(scope.row)" class="icon-e" text type="success">预览</el-button>
									<el-button @click="downClick(scope.row)" class="icon-e" text type="warning">下载</el-button>
									<el-button @click="delClick(scope.row.id)" class="icon-e" text type="danger">删除</el-button>
								</template>
							</el-table-column>
						</el-table>
					</el-tab-pane>
				</el-tabs>
			</el-col>
		</el-row>
	</el-dialog>
</template>
<style scoped></style>
